/**
 * JAVACC DEMO 1.0
 */
package com.apache.excp.core.impl.exp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.apache.excp.ConfigConstant;
import com.apache.excp.core.manager.ExportExecl;
import com.apache.excp.core.model.ExportVo;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * description:  按指定模板导出word文件
 * @author Hou Dayu 创建时间：2016-7-29
 */
public class ExportWordImpl implements ExportExecl {

	private Logger log = Logger.getLogger(ExportWordImpl.class);

	/**
	 * TODO 按指定模板导出word文件实现.  
	 * 步骤:第一步将写好的word方件另存为xml文件;
	 *      第二步修改对应数据为freemarker语法;
	 *      第三步将文件后缀改为.ftl;
	 *      第四步调用接口生成word文件;  
	 */
	public Object exportData(ExportVo vo) {

		String path = vo.getFilePath();
		if (ConfigConstant.isNull(path)) {
			path = ConfigConstant.getClassLoaderPath().replace("WEB-INF/classes/", "downloadFile/");
		}
		ConfigConstant.newCreateFolder(path);
        FileOutputStream fos=null;
        Writer out=null;
		try {
			Template temp = configTemplate(vo.getTemplateName());
			fos = new FileOutputStream(path + vo.getNewFileName());
			out = new OutputStreamWriter(fos, "UTF-8");
			temp.process(vo.getParams(), out);
			out.flush();
		} catch (Exception e) {
			log.error(e);
		}finally{
            IOUtils.closeQuietly(out);
            IOUtils.closeQuietly(fos);
        }
		return null;
	}

	/**
	 * description:  获取模板模型
	 * @param tempName 模板名称
	 * @return
	 * @throws IOException   
	 * @author Hou Dayu  
	 * @update 2014-7-29
	 */
	private Template configTemplate(String tempName) throws IOException {
		Configuration config = new Configuration();
		//设置编码
		config.setDefaultEncoding("UTF-8");
		//ftl模板文件统一放至 com.lun.template 包下面
		config.setClassForTemplateLoading(this.getClass(), "/templates");
		config.setObjectWrapper(new DefaultObjectWrapper());
		Template template = config.getTemplate(tempName);
		return template;
	}

}
